import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:toys_flutter/api/app.dart';
import 'package:toys_flutter/components/RefreshableListView.dart';

class NewsPage extends StatefulWidget {
  const NewsPage({super.key});

  @override
  _NewsPageState createState() => _NewsPageState();
}

class _NewsPageState extends State<NewsPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  List<Map<String, dynamic>> _navList = [];
  List<Map<String, dynamic>> _list = [];
  int page = 1;
  bool isMore = true;
  String _navId = '';

  @override
  void initState() {
    super.initState();
    _getNav().then((_) {
      _tabController = TabController(length: _navList.length, vsync: this);
      _tabController.addListener(_onTabChanged);
      _fetchData();
    });
  }

  Future<void> _getNav() async {
    try {
      var res = await Api.articleCategory();
      if (res['code'] == 1) {
        setState(() {
          _navList = List<Map<String, dynamic>>.from(res['data'] ?? []);
          _navId = res['data'][0]['id'].toString();
        });
      } else {
        _showError('加载失败，请重试');
      }
    } catch (e) {
      _showError('网络错误，请重试');
    }
  }

  void _onTabChanged() {
    if (_tabController.indexIsChanging) {
      setState(() {
        _navId = _navList[_tabController.index]['id'].toString();
        page = 1; // Reset page number when tab changes
        _fetchData();
      });
    }
  }

  Future<void> _fetchData() async {
    try {
      var res =
          await Api.articleLists({'type': 0, 'id': _navId, 'page_no': page});
      if (res['code'] == 1) {
        setState(() {
          if (page == 1) {
            _list = List<Map<String, dynamic>>.from(res['data']['list'] ?? []);
          } else {
            _list.addAll(
                List<Map<String, dynamic>>.from(res['data']['list'] ?? []));
          }
          isMore = res['data']['more'] != 0;
        });
      } else {
        _showError('加载失败，请重试');
      }
    } catch (e) {
      _showError('网络错误，请重试');
    }
  }

  Future<void> onLoadMore() async {
    if (!isMore) return;
    page++;
    await _fetchData();
  }

  Future<void> _refreshData() async {
    page = 1;
    await _fetchData();
  }

  void _showError(String message) {
    TDToast.showIconText(
      message,
      icon: TDIcons.error,
      direction: IconTextDirection.vertical,
      context: context,
    );
  }

  @override
  void dispose() {
    _tabController.removeListener(_onTabChanged);
    _tabController.dispose(); // 释放控制器
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    const Color colorMain = Color.fromRGBO(211, 173, 247, 1);

    return Scaffold(
      appBar: AppBar(
        title: _navList.isNotEmpty
            ? SizedBox(
                width: 240,
                child: TDTabBar(
                  indicatorPadding: EdgeInsets.zero,
                  labelPadding: EdgeInsets.zero,
                  tabs: List.generate(
                    _navList.length,
                    (index) => TDTab(text: _navList[index]['name']),
                  ),
                  controller: _tabController,
                  showIndicator: true,
                  dividerHeight: 0,
                ),
              )
            : null,
        backgroundColor: colorMain,
      ),
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              colorMain,
              Colors.white,
              Colors.white,
              Colors.white,
            ],
          ),
        ),
        child: RefreshableListView(
          enableLoadMore: true,
          onLoadMore: onLoadMore,
          onRefresh: _refreshData,
          children: [
            ...List.generate(
              _list.length,
              (index) => Padding(
                padding: const EdgeInsets.fromLTRB(15, 5, 15, 15),
                child: _buildItem(context, _list[index]),
              ),
            ),
            const SizedBox(height: 20),
            if (!isMore)
              const TDDivider(
                text: '没有更多了',
                alignment: TextAlignment.center,
              ),
            const SizedBox(height: 20),
          ],
        ),
      ),
    );
  }

  Widget _buildItem(BuildContext context, Map<String, dynamic> item) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Text(
                  item['title'],
                  style: const TextStyle(fontSize: 14, color: Colors.black),
                ),
                const SizedBox(height: 5),
                Text(
                  item['synopsis'],
                  style: const TextStyle(fontSize: 12, color: Colors.black54),
                ),
              ],
            ),
            const SizedBox(width: 10),
            TDImage(
              width: 90,
              height: 80,
              imgUrl: item['image'] ?? 'images/avatar.png',
              fit: BoxFit.cover,
              type: TDImageType.roundedSquare,
            ),
          ],
        ),
        const SizedBox(height: 10),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text('发布时间：${item["create_time"]}',
                style: const TextStyle(fontSize: 12, color: Colors.black54)),
            Text('${item["visit"]} 人阅读',
                style: const TextStyle(fontSize: 12, color: Colors.black54)),
          ],
        ),
        const SizedBox(height: 10),
        const TDDivider(),
      ],
    );
  }
}
